package com.jic.interaction.ChinaPost.sever;

import com.jic.interaction.common.enums.RedisKey;
import com.jic.interaction.common.utils.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Component
@Slf4j
@EnableScheduling
public class GetSign {
    @Autowired
    RedisService redisService;
    @Value("wz.appid")
    private String applyId;

    public String getSign(String jsonUser) {
        List<String> list = new ArrayList<>();
        String singTicket = redisService.getValue(RedisKey.WZ_SING_TICKET);
        if (singTicket==null || singTicket.equals("")){
            log.error("singTicket为空，计算sign失败");
            return null;
        }
        String nonceStr = UUID.randomUUID().toString();

        list.add(applyId);
        list.add(nonceStr);
        list.add("1.0.0");
        list.add(jsonUser);
        //String sign = sign(list,"8Xogitd76n8YDJiQCBXefyBtRKV6tGDCOOuQJvc910qvm00dIxjCuePJrx8IGsQU");
        String sign = sign(list, singTicket);
        return sign;
    }


    private String sign(List<String> values, String signTicket) {
        if (values == null) {
            throw new NullPointerException("values is null");
        }
        values.removeAll(Collections.singleton(null));// remove null
        values.add(signTicket);
        java.util.Collections.sort(values);
        StringBuilder sb = new StringBuilder();
        for (String s : values) {
            sb.append(s);
        }
        try {
            MessageDigest md = MessageDigest.getInstance("sha1");
            md.update(sb.toString().getBytes("UTF-8"));
            String sign = bytesToHex(md.digest());
            return sign;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String bytesToHex(byte[] bArr) {
        StringBuffer sb = new StringBuffer(bArr.length);
        String sTmp;

        for (int i = 0; i < bArr.length; i++) {
            sTmp = Integer.toHexString(0xFF & bArr[i]);
            if (sTmp.length() < 2)
                sb.append(0);
            sb.append(sTmp.toUpperCase());
        }

        return sb.toString();
    }
}
